#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Build script for Muto Hexapod Robot Control Library

This script helps build and package the library for distribution.

Usage:
    python build.py [command]
    
Commands:
    clean       - Clean build artifacts
    build       - Build the package
    install     - Install the package locally
    develop     - Install in development mode
    upload      - Upload to PyPI (requires credentials)
    check       - Check package integrity
    all         - Clean, build, and check
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path


def run_command(cmd, check=True):
    """Run a shell command and return the result."""
    print(f"Running: {cmd}")
    try:
        result = subprocess.run(cmd, shell=True, check=check, 
                              capture_output=True, text=True)
        if result.stdout:
            print(result.stdout)
        return result
    except subprocess.CalledProcessError as e:
        print(f"Error running command: {e}")
        if e.stderr:
            print(f"Error output: {e.stderr}")
        sys.exit(1)


def clean():
    """Clean build artifacts."""
    print("Cleaning build artifacts...")
    
    # Directories to clean
    clean_dirs = [
        "build",
        "dist", 
        "*.egg-info",
        "__pycache__",
        ".pytest_cache",
        ".mypy_cache",
        ".coverage",
        "htmlcov"
    ]
    
    for pattern in clean_dirs:
        if "*" in pattern:
            # Use shell expansion for wildcards
            run_command(f"rm -rf {pattern}", check=False)
        else:
            path = Path(pattern)
            if path.exists():
                if path.is_dir():
                    shutil.rmtree(path)
                    print(f"Removed directory: {path}")
                else:
                    path.unlink()
                    print(f"Removed file: {path}")
    
    # Clean Python cache files
    run_command("find . -name '*.pyc' -delete", check=False)
    run_command("find . -name '__pycache__' -type d -exec rm -rf {} +", check=False)
    
    print("Clean completed.")


def build():
    """Build the package."""
    print("Building package...")
    
    # Build source distribution and wheel
    run_command("python -m build")
    
    print("Build completed.")


def install():
    """Install the package locally."""
    print("Installing package locally...")
    
    # Install from source
    run_command("pip install .")
    
    print("Installation completed.")


def develop():
    """Install in development mode."""
    print("Installing in development mode...")
    
    # Install in editable mode with dev dependencies
    run_command("pip install -e .[dev]")
    
    print("Development installation completed.")


def upload():
    """Upload to PyPI."""
    print("Uploading to PyPI...")
    
    # Check if twine is installed
    try:
        run_command("twine --version")
    except:
        print("Installing twine...")
        run_command("pip install twine")
    
    # Upload to PyPI
    run_command("twine upload dist/*")
    
    print("Upload completed.")


def check():
    """Check package integrity."""
    print("Checking package integrity...")
    
    # Check package metadata
    run_command("python setup.py check --metadata --strict")
    
    # Check distribution
    if Path("dist").exists():
        run_command("twine check dist/*")
    
    # Run basic import test
    try:
        run_command("python -c 'import muto_hexapod_lib; print(muto_hexapod_lib.get_version())'")
        print("✓ Package import test passed")
    except:
        print("✗ Package import test failed")
    
    print("Check completed.")


def run_tests():
    """Run test suite."""
    print("Running tests...")
    
    # Check if pytest is available
    try:
        run_command("pytest --version")
        run_command("pytest tests/ -v")
    except:
        print("pytest not available, skipping tests")
    
    print("Tests completed.")


def lint():
    """Run code linting."""
    print("Running code linting...")
    
    # Run flake8
    try:
        run_command("flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics")
        print("✓ Flake8 check passed")
    except:
        print("✗ Flake8 check failed")
    
    # Run black check
    try:
        run_command("black --check .")
        print("✓ Black formatting check passed")
    except:
        print("✗ Black formatting check failed")
    
    print("Linting completed.")


def format_code():
    """Format code with black."""
    print("Formatting code...")
    
    try:
        run_command("black .")
        print("✓ Code formatted with black")
    except:
        print("✗ Black formatting failed")
    
    print("Formatting completed.")


def all_tasks():
    """Run all build tasks."""
    print("Running all build tasks...")
    
    clean()
    lint()
    build()
    check()
    
    print("All tasks completed.")


def main():
    """Main entry point."""
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(1)
    
    command = sys.argv[1].lower()
    
    commands = {
        "clean": clean,
        "build": build,
        "install": install,
        "develop": develop,
        "upload": upload,
        "check": check,
        "test": run_tests,
        "lint": lint,
        "format": format_code,
        "all": all_tasks,
    }
    
    if command in commands:
        commands[command]()
    else:
        print(f"Unknown command: {command}")
        print(__doc__)
        sys.exit(1)


if __name__ == "__main__":
    main()